<template>
  <div class="app-container">
    <el-form :inline="true"
             ref="refForm"
             :model="form">
      <el-form-item label="查询时间"
                    prop="time">
        <el-date-picker v-model="form.time"
                        type="daterange"
                        align="right"
                        unlink-panels
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        value-format="yyyy-MM-dd">
        </el-date-picker>
      </el-form-item>
      <el-form-item v-if="roleCheck('virtual')"
                    class="with-pre-select"
                    label="数据类型">
        <el-select v-model="form.isFake">
          <el-option v-for="item in consts.STATISTICS_RANGE"
                     :key="item.value"
                     :label="item.title"
                     :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-button class="filter-item"
                 type="primary"
                 icon="el-icon-download"
                 @click="exportHandle">导出</el-button>
      <el-button class="filter-item"
                 type="primary"
                 icon="el-icon-search"
                 @click="submitFilterForm">搜索</el-button>
    </el-form>
    <el-table show-summary
              :summary-method="getSummaries"
              border
              :data="tableData"
              v-loading="loading"
              element-loading-text="加载中..."
              class="el-table-align-center">
      <el-table-column label="时间"
                       align="center"
                       prop="day"
                       width="100">
        <template slot-scope="{row}">
          <div v-if="row.day">{{Number(row.day) | toTime('YYYY-MM-DD')}}</div>
          <div v-else>{{form.time[0]}}</div>
        </template>
      </el-table-column>
      <el-table-column v-if="roleCheck('detail')"
                       align="center"
                       label="查看明细"
                       prop="time"
                       width="180">
        <template slot-scope="{row}">
          <el-button type="text"
                     @click="openDialog({props: row, dialogName: 'custom-dialog'})">今日余额明细</el-button>
        </template>
      </el-table-column>
      <el-table-column v-for="(item,index) in gamesBalance"
                       :key="index+'gamesBalance'"
                       align="center"
                       :prop="item.prop"
                       :label="item.label">
        <template slot-scope="{row}">
          {{row[item.prop] | currency}}
        </template>
      </el-table-column>

    </el-table>

    <custom-dialog :visible="dialogVisible"
                   returnButtonName="返回上一层"
                   :callback="closeDialog">
      <div slot="title">&nbsp;</div>
      <statistics-balance-today :row-data="dialogProps"
                                v-if="dialogVisible" />
    </custom-dialog>
  </div>
</template>


<script>
import { getStatisticalBalance, exportAccountBalance } from '@/services/api/statistical';
import { currencyToNumber } from '@/filters';
import {
  form, grid, dialog, handleDownload,
} from '@/build';
import CustomDialog from '@/components/customDialog/index';
import StatisticsBalanceToday from '@/views/statistics/balanceToday';

export default {
  name: 'statistics-balance',
  components: { StatisticsBalanceToday, CustomDialog },
  mixins: [form, grid, dialog, handleDownload],
  data() {
    // let times = _.toPeriod({
    //   start: [-1, 'days'],
    //   end: [0, 'days'],
    //   format: 'YYYY-MM-DD'
    // });
    // 本月时间本月1号至当前时间
    const monthTime = [moment().startOf('month').format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')];

    return {
      tableData: [],
      form: {
        time: monthTime,
        isFake: 0,
      },
      filters: {
        startDate: moment(monthTime[0]).format('YYYY-MM-DD'),
        endDate: moment(monthTime[1]).format('YYYY-MM-DD'),
        isFake: 0,
      },
      filterDateType: false,
      gamesBalance: [
        {
          prop: 'agTotal',
          label: 'AG平台余额',
        },
        {
          prop: 'ptTotal',
          label: 'PT平台余额',
        },
        {
          prop: 'ebetTotal',
          label: 'eBET平台余额',
        },
        {
          prop: 'xj188Total',
          label: '贝博体育',
        },
        {
          prop: 'lbTotal',
          label: 'LB彩票',
        },
        {
          prop: 'hlTotal',
          label: '欢乐棋牌',
        },
        {
          prop: 'gmqpTotal',
          label: '贝博棋牌',
        },
        {
          prop: 'xjLiveTotal',
          label: '小金真人',
        },
        {
          prop: 'swLotteryTotal',
          label: '双赢彩票',
        },
        {
          prop: 'ppTotal',
          label: 'PP电子',
        },
        {
          prop: 'fiveGMTotal',
          label: '5GM彩票',
        },
        {
          prop: 'mwTotal',
          label: 'MW平台',
        },
        {
          prop: 'imEsportTotal',
          label: 'IM电竞',
        },
        // {
        //   prop: 'virtualSportTotal',
        //   label: '虚拟体育',
        // },
        {
          prop: 'balanceTotal',
          label: '中心钱包',
        },
        {
          prop: 'total',
          label: '汇总余额',
        },
      ],
    };
  },
  methods: {
    submitFilterForm() {
      const { time, isFake } = this.form;
      let startDate; let
        endDate;
      if (!_.isUndefined(time) && _.isArray(time)) {
        startDate = moment(time[0]).format('YYYY-MM-DD');
        endDate = moment(time[1]).format('YYYY-MM-DD');
      }
      this.filters = {
        ...this.filters, startDate, endDate, isFake,
      };
      this.getAll();
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '汇总';
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return _.currency(currencyToNumber(prev) + parseFloat(currencyToNumber(curr)));
            }
            return _.currency(prev);
          }, 0);
        } else {
          sums[index] = '';
        }
      });

      return sums;
    },
    // 导出
    exportHandle() {
      const { time, isFake } = this.form;
      let startDate; let
        endDate;
      if (!_.isUndefined(time) && _.isArray(time)) {
        startDate = moment(time[0]).format('YYYY-MM-DD');
        endDate = moment(time[1]).format('YYYY-MM-DD');
      }
      const ajaxData = { startDate, endDate, isFake };
      const filename = '账户余额统计明细报表.csv';
      const header = ['时间', 'AG平台余额', 'PT平台余额', 'eBET平台余额', '贝博体育', 'LB彩票', '欢乐棋牌', '贝博棋牌', '小金真人', '双赢彩票', 'PP电子', '5GM彩票', 'MW捕鱼', 'IM电竞', '中心钱包', '汇总余额'];
      const filterField = ['day', 'agTotal', 'ptTotal', 'ebetTotal', 'xj188Total', 'lbTotal', 'hlTotal', 'gmqpTotal', 'xjLiveTotal', 'swLotteryTotal', 'ppTotal', 'fiveGMTotal', 'mwTotal', 'imEsportTotal', 'balanceTotal', 'total'];
      exportAccountBalance(ajaxData).then(([result, data]) => {
        if (result) {
          const exportData = this.responseFormatter(data);
          this.export2Excel(header, filterField, exportData, filename);
        } else {
          this.$message({ message: `导出失败,${data.message}`, type: 'warning' });
        }
      });
    },
    // 格式化导出数据
    responseFormatter(data) {
      data.map((item) => {
        item.agTotal = _.currency(item.agTotal);
        item.ptTotal = _.currency(item.ptTotal);
        item.ebetTotal = _.currency(item.ebetTotal);
        item.bettingSum = _.currency(item.bettingSum);
        item.xj188Total = _.currency(item.xj188Total);
        item.xjLiveTotal = _.currency(item.xjLiveTotal);
        item.lbTotal = _.currency(item.lbTotal);
        item.hlTotal = _.currency(item.hlTotal);
        item.gmqpTotal = _.currency(item.gmqpTotal);
        item.swLotteryTotal = _.currency(item.swLotteryTotal);
        item.ppTotal = _.currency(item.ppTotal);
        item.fiveGMTotal = _.currency(item.fiveGMTotal);
        item.mwTotal = _.currency(item.mwTotal);
        item.imEsportTotal = _.currency(item.imEsportTotal);
        // item.virtualSportTotal = _.currency(item.virtualSportTotal);
        item.balanceTotal = _.currency(item.balanceTotal);
        item.total = _.currency(item.total);
        item.day = _.toDate(Number(item.day));
      });

      return data;
    },
  },
  mounted() {
    this.bindGet(getStatisticalBalance, 'tableData', {
      sendingData: 'filters',
      // format: data =>
      // let arr = Object.values(data).map((item, index) => {
      //   let obj = {
      //     day: Object.keys(data)[index]
      //   }
      //   Object.keys(item).forEach(key => {
      //     let value = consts.GAME_ID.find(item => {
      //       return item.channelId == key
      //     })
      //     if (value) {
      //       obj[value.channelName_en] = item[key]
      //     } else if (key == 0) {
      //       obj.wallet_center = item[key]
      //     }
      //   })
      //   obj.sum = Object.values(item).reduce((sum, cur) => {
      //     return sum + cur
      //   })
      //   return obj
      // })
    });
    this.getAll();
  },
};
</script>

<style lang="scss" scoped>
.with-pre-select {
  .el-input-group__prepend {
    .el-select {
      width: 120px;
    }
  }
}
</style>
